package com.whl.sm.service.impl.repair;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.repair.DataOperateLogMapper;
import com.whl.sm.model.repair.DataOperateLog;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.repair.DataOperateLogService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-11-28
 */
@Slf4j
@Service
public class DataOperateLogServiceImpl extends ServiceImpl<DataOperateLogMapper, DataOperateLog> implements DataOperateLogService {

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;


    @Override
    public Result update(DataOperateLog dataOperateLog) {
        try{
            if (Objects.isNull(dataOperateLog.getId())){
                getBaseMapper().insert(dataOperateLog);
            }else {
                getBaseMapper().updateById(dataOperateLog);
            }
        }catch (Exception e){
            log.error("操作日志纪录更新异常:"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result addOperateLog(String dataId, String dataTye, String remark) {
        try {
            DataOperateLog insertLog = new DataOperateLog();
            insertLog.setDataId(dataId);
            insertLog.setDataType(dataTye);
            insertLog.setOperateRemark(remark);
            insertLog.setUpdateOperator(orgUserService.getCurrentUserId());
            getBaseMapper().insert(insertLog);
        }catch (Exception e){
            log.error(remark+"日志记录异常:"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }


    @Override
    public List<DataOperateLog> getByDataId(String dataId) {
        try{
            List<DataOperateLog> linkData = getBaseMapper().selectList(new QueryWrapper<DataOperateLog>()
                    .eq("data_id",dataId)
                    .orderByDesc("update_time")
            );
            if (linkData.size()>0){
                linkData.stream().forEach(obj->{
                    OrgUserInfo operator = orgUserInfoService.getByUserId(obj.getUpdateOperator());
                    obj.setUpdateOperatorName(operator==null?"":operator.getUserName());
                });
            }
            return linkData;
        }catch (Exception e){
            log.error("操作日志获取失败:"+e.getMessage());
            return new ArrayList<>();
        }
    }

}
